package com.kangfawei.thread;

import java.util.Random;

/**
 * @author 康发伟
 * 模拟龟兔赛跑
 */
public class Race implements Runnable {
    // 获胜者
    private String winner;
    private Integer sleepStep = new Random().nextInt(100);

    @Override
    public void run() {

        for (int step = 1; step <= 100; step++) {
           try {
               // 乌龟跑的慢
               if (Thread.currentThread().getName().equals("乌龟")) {
                   Thread.sleep(2);
               } else {
                   Thread.sleep(1);
                   // 兔子在100步之内随机一个时间睡一觉

                   if(step == sleepStep){
                       Thread.sleep(200);
                       System.out.println("兔子在第"+step+"步时睡了一觉！");
                   }
               }
           }catch (InterruptedException e) {
               e.printStackTrace();
           }

            System.out.println(Thread.currentThread().getName()+"跑了第" + step + "步");
            if(stop(step)){
                break;
            }
        }
    }

    // 判断比赛结束
    private boolean stop(int step){
        if(winner != null){
            return true;
        }if(step == 100){
            winner = Thread.currentThread().getName();
            System.out.println(winner + "胜利");
            return true;
        }
        return false;
    }

    public static void main(String[] args) {
        Race race = new Race();
        new Thread(race,"兔子").start();
        new Thread(race,"乌龟").start();
    }
}
